<!-- 路径规划 -->
<template>
  <div class="">
    <PagePanel :panelTitle="activePanel.panelTitle" @clickClose="clickClose">
      <el-card class="box-card"
        >提示：地图上点击选中快递点起点和终点，开始路径规划，最后显示动态路径动画。</el-card
      >
      <el-card style="margin-top: 10px" class="box-card">
        <div slot="header" class="clearfix">
          <span>1、起止点信息</span>
        </div>
        <div>
          <span>起始点</span
          ><el-input v-model="startPosition" style="width: 150px"></el-input
          ><el-button
            @click="pickStartPosition(1)"
            small
            icon="el-icon-location"
          ></el-button>
        </div>
        <div>
          <span>终止点</span
          ><el-input v-model="endPosition" style="width: 150px"></el-input
          ><el-button
            @click="pickStartPosition(2)"
            small
            icon="el-icon-location"
          ></el-button>
        </div>
      </el-card>
      <el-card style="margin-top: 10px" class="box-card">
        <div slot="header" class="clearfix">
          <span>2、路径规划</span>
        </div>
        <!-- <div v-for="o in 4" :key="o" class="text item">
          {{ "关联门牌信息 " + o }}
        </div> -->
        <el-button @click="start">开始路径规划</el-button>
        <el-button @click="startAnimation">开始动画</el-button>
      </el-card>
    </PagePanel>
  </div>
</template>

<script>
import PagePanel from '@/components/PagePanel'
import request from '@/utils/request.js'
import { getDeliveryList, routePlan } from '@/api/home.js'
// import XMLResolve from '@/utils/XMLResolve.js'
// import tdt_jsonp from '@/utils/jsonp.js'
import markerImg from '../../../assets/img/car2.png'

const Cesium = window.Cesium
const DeliveryEntityName = 'delivery'

export default {
  name: 'routePlan',
  components: { PagePanel },
  data () {
    return {
      pickMode: 1,
      startPosition: '',
      endPosition: '',
      routeEntity: null // 规划的路径
    }
  },
  computed: {
    activePanel () {
      return this.$store.state.activePanel
    }
  },
  mounted () {
    // 地图重置

    this.loadGisData()
    this.initGisEvent()
  },
  methods: {
    clickClose () {
      console.log('@@@@@@@@@@@@', this.activePanel)
    },

    // 快递点
    loadGisData () {
      getDeliveryList({ page: 1, pageSize: 10 }).then((response) => {
        const data = JSON.parse(response.data)
        const entities = []
        data.data.map((delivery) => {
          const pt = delivery.position.split(',')
          const entity = window.cesiumViewer.entities.add({
            name: 'delivery',
            position: Cesium.Cartesian3.fromDegrees(
              Number(pt[0]),
              Number(pt[1])
            ),
            point: {
              color: Cesium.Color.RED,
              pixelSize: 15,
              heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
              disableDepthTestDistance: Number.POSITIVE_INFINITY // 无论如何缩放，标记点不被地形遮挡
            },
            label: {
              fillColor: Cesium.Color.LIGHTBLUE,
              // outlineColor: Cesium.Color.WHITE,
              // outlineWidth: 1,
              text: delivery.name,
              font: '20px sans-serif',
              pixelOffset: new Cesium.Cartesian2(0.0, -30),
              disableDepthTestDistance: Number.POSITIVE_INFINITY // 去掉地形遮挡
            }
          })
          entities.push(entity)
        })

        entities.map((entity) => {
          entity.name = DeliveryEntityName
        })

        // window.cesiumViewer.flyTo(entities)
      })
    },

    pickStartPosition (mode) {
      this.pickMode = mode
    },

    initGisEvent () {
      const handler = new Cesium.ScreenSpaceEventHandler(
        window.cesiumViewer.scene.canvas
      )
      handler.setInputAction((event) => {
        const pickedEntity = window.cesiumViewer.scene.pick(event.position)
        console.log(pickedEntity)
        if (pickedEntity?.id?.name === DeliveryEntityName) {
          const cartographic = Cesium.Cartographic.fromCartesian(
            pickedEntity.id.position.getValue()
          )
          const posStr =
            Cesium.Math.toDegrees(cartographic.longitude) +
            ',' +
            Cesium.Math.toDegrees(cartographic.latitude)
          if (this.pickMode === 1) {
            this.startPosition = posStr
          } else {
            this.endPosition = posStr
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    },

    start () {
      if (this.startPosition === '' || this.endPosition === '') {
        console.log('设置起止点')
        return
      }

      this.routePlan(this.startPosition, this.endPosition)
    },

    /**
     * 路径规划
     * @param {} start 'x,y' 经纬度
     * @param {} end 'x,y' 经纬度
     */
    routePlan (start, end) {
      routePlan({ start, end }).then((response) => {
        const data = JSON.parse(response.data)
        console.log(data)
        const pts = []
        for (let i = 0; i < data.length; i += 2) {
          pts.push(data[i], data[i + 1])
        }
        const line = window.cesiumViewer.entities.add({
          name: 'line',
          polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(pts),
            width: 10,
            arcType: Cesium.ArcType.RHUMB,
            material: Cesium.Color.GREEN
          }
        })
        window.cesiumViewer.zoomTo(line)

        // startAnimation(line)
        this.routeEntity = line
      })

      // const viewer = window.cesiumViewer
      // const apiUrl = `http://api.tianditu.gov.cn/drive?postStr={"orig":"${start}","dest":"${end}","style":"0"}&type=search&tk=b88cc8129fe0cd5595a5551efe937c5f`
      // tdt_jsonp(apiUrl).then((res) => {
      //   console.log(res)
      //   const xmlResult = res // res.data;
      //   // viewer
      //   const result = XMLResolve(xmlResult)
      //   console.log(result)
      //   let routeInfoNode = null
      //   Object.keys(result.documentElement.childNodes).map((key) => {
      //     if (
      //       result.documentElement.childNodes[key].tagName === 'routelatlon'
      //     ) {
      //       routeInfoNode = result.documentElement.childNodes[key]
      //     }
      //   })
      //   if (!routeInfoNode) return
      //   // 'x,y;x,y;...'
      //   const routeStr = routeInfoNode.textContent
      //   console.log(routeStr)
      //   const pts = []
      //   routeStr.split(';').map((xystr) => {
      //     if (xystr.indexOf(',') === -1) return
      //     const xy = xystr.split(',')
      //     pts.push(Number(xy[0]), Number(xy[1]))
      //   })
      //   const line = viewer.entities.add({
      //     name: 'line',
      //     polyline: {
      //       positions: Cesium.Cartesian3.fromDegreesArray(pts),
      //       width: 10,
      //       arcType: Cesium.ArcType.RHUMB,
      //       material: Cesium.Color.GREEN
      //     }
      //   })
      //   viewer.zoomTo(line)

      //   // startAnimation(line)
      //   this.routeEntity = line
      // })
    },

    startAnimation () {
      const entity = this.routeEntity
      const viewer = window.cesiumViewer
      const positions = entity.polyline.positions.getValue()

      let index = 0
      const pts = [positions[index]]

      const updatePoints = function () {
        if (pts.length < positions.length) {
          pts.push(positions[++index])
        //   // console.log(index);
        //   // 当前进度
        //   const percent = index * 100 / positions.length
        //   if (statusChanged)statusChanged({ percent })
        }
      }

      const redLine = viewer.entities.add({
        polyline: {
          // This callback updates positions each frame.
          positions: new Cesium.CallbackProperty(function (time, result) {
            // if(pts.length < positions.length){
            //     pts.push(positions[++index]);
            //     console.log(index);
            // }
            // return pts; //Cesium.Cartesian3.fromDegreesArray(pts, Cesium.Ellipsoid.WGS84, result );
            return pts
          }, false),
          width: 10,
          material: Cesium.Color.RED,
          zIndex: 100,
          clampToGround: true
        }
      })

      const getLength = function getLength (time, result) {
        // Get the end position from the polyLine's callback.
        const endPoint = redLine.polyline.positions.getValue(time, result)[1]
        endCartographic = Cesium.Cartographic.fromCartesian(endPoint)

        geodesic.setEndPoints(startCartographic, endCartographic)
        const lengthInMeters = Math.round(geodesic.surfaceDistance)
        return `${(lengthInMeters / 1000).toFixed(1)} km`
      }

      const getText = function (time, result) {
        const points = redLine.polyline.positions.getValue(time, result)
        const index = points.length
        // entity.properties
        // return '当前线路：' + entity.name;
        return '当前目标'
      }

      const getMidpoint = function (time, result) {
        // Get the end position from the polyLine's callback.
        const endPoint = redLine.polyline.positions.getValue(time, result)[1]
        endCartographic = Cesium.Cartographic.fromCartesian(endPoint)

        geodesic.setEndPoints(startCartographic, endCartographic)
        const midpointCartographic = geodesic.interpolateUsingFraction(
          0.5,
          scratch
        )
        return Cesium.Cartesian3.fromRadians(
          midpointCartographic.longitude,
          midpointCartographic.latitude
        )
      }

      const getEndPoint = function (time, result) {
        const pts = redLine.polyline.positions.getValue(time, result)
        const endPoint = pts[pts.length - 1]
        // console.log('当前位置：',endPoint);
        return endPoint
      }

      const getRotation = function (time, result) {
        const points = redLine.polyline.positions.getValue(time, result)
        if (points.length < 2) return 0.0
        const currPt = points[points.length - 1]
        const lastPt = points[points.length - 2]
        const transform = Cesium.Transforms.eastNorthUpToFixedFrame(lastPt)
        const positionvector = Cesium.Cartesian3.subtract(currPt, lastPt, new Cesium.Cartesian3())
        const vector = Cesium.Matrix4.multiplyByPointAsVector(Cesium.Matrix4.inverse(transform, new Cesium.Matrix4()), positionvector, new Cesium.Cartesian3())
        const direction = Cesium.Cartesian3.normalize(vector, new Cesium.Cartesian3())
        const heading = Math.atan2(direction.y, direction.x)
        return Cesium.Math.zeroToTwoPi(heading)
      }

      //   // Label the polyline with calculated length.
      const label = viewer.entities.add({
        position: new Cesium.CallbackProperty(getEndPoint, false),
        // label: {
        //   // This callback updates the length to print each frame.
        //   //   text: new Cesium.CallbackProperty(getLength, false),
        //   text: new Cesium.CallbackProperty(getText, false),
        //   font: "20px sans-serif",
        //   fillColor: Cesium.Color.RED,
        //   pixelOffset: new Cesium.Cartesian2(0.0, -64),
        //   disableDepthTestDistance: Number.POSITIVE_INFINITY, // 去掉地形遮挡
        // },
        billboard: {
          show: true,
          image: markerImg,
          pixelOffset: new Cesium.Cartesian2(0.0, -20),
          disableDepthTestDistance: Number.POSITIVE_INFINITY, // 去掉地形遮挡
          rotation: new Cesium.CallbackProperty(getRotation, false),
          width: 64,
          height: 32
        }
      })

      setInterval(updatePoints, 500)
    }
  },
  beforeDestroy () {
    // 因为面板都是用的v-if，会销毁面板，需要销毁的事件也可以写这里
    // 移除数据
    window.cesiumViewer.entities.values.map((entity) => {
      if (entity.id.name === DeliveryEntityName) {
        window.cesiumViewer.entities.remove(entity)
      }
    })
  }
}
</script>
<style lang="less" scoped></style>
